<?php include "../public/header.php"?>
<link rel="stylesheet" href="/static/admin/css/course.css">
<style>
    .hei{min-height: 244px;background: #ecf0f1;padding: 0 20px;padding-bottom: 60px}
    .layui-form-label{width: 102px!important;}
    .laypage-top-div{text-align: right;background-color: #FFFFFF;position: fixed;bottom: 0;width: 100%;}
    .laypage-top-div button{margin: 15px 15px 15px 0!important;}
    .laypage-top-div button i{margin-right: 5px}
    .seadiv{height: 60px;width: 100%;background-color: #E5E5E5;}
    .seadiv .banben{margin-top: 11px}
    .seadiv .lastupddt{margin-left: 10px}
    .seadiv .isstatus{margin-left: 10px;color: #aaaaaa}
    .seadiv .isstatus i{font-size: 12px;margin-right: 5px}
    .isstatus .dian{width: 7px;height: 7px;border-radius: 100%;display: inline-block;margin-right: 7px;}

    .layui-dropdown{margin: 0}
    .layui-menu{margin: 0;}
    .layui-menu li{display: table-cell;text-align:center;padding: 10px 15px}
    .layui-menu li .iconbut{border:1px solid #ABABAB;border-radius:100%;width:40px;height: 40px;display: inline-block;margin-bottom: 5px}
    .layui-menu li i{font-size: 30px;color:#2780EC;line-height: 40px}

    .mapsidediv{overflow: auto;display: grid;background-color: #FFFFFF}
    .nonedata{display: none}
    .iserrorheader{background-color: red!important;}
    .iserrorsection{border: 3px solid red!important;}
    .btn{padding: 0;margin: 0}
    .layui-menu li:hover {
        background-color: #F6F6F6 !important;
        color: #000000 !important;
    }

    #gaikuai{
        width: 100%;position: absolute;z-index: 99999;background: rgba(0,0,0,0.5);
        font-weight: bold;font-size: 18px;color: #FFFFFF;padding-top: 50px;
        height: 200px;top: 200px;
    }
</style>
<body class="add_body" id="body">
<div class="layuimini-container" id="commentForm">
    <div class="page-title">
        <div class="page-title-con">
            <span>编辑流程</span><div class="move_title"></div>
            <div class="page-title-opt-list">
                <button type="button" class="layui-btn layui-btn-sm btn-light marginr5 post_sub_del" lay-submit="" lay-filter="add">删除</button>
                <button type="button" class="layui-btn layui-btn-sm btn-dark marginr5 post_sub" lay-submit="" lay-filter="add">保存</button>
                <button type="button" class="layui-btn layui-btn-sm btn-dark marginr5 post_sub2" lay-submit="" lay-filter="add">保存为新版本</button>
                <button type="button" class="layui-btn layui-btn-sm btn-dark marginr5 post_sub3" lay-submit="" lay-filter="add">发布</button>
                <span id="page-close" class="page-close" onclick="layer_close()">×</span>
            </div>
        </div>
    </div>
    <div class="hei">
        <div style="height: 70px"></div>
        <div class="seadiv">
            <form class="layui-form" lay-filter="form-add">
                <div class="layui-inline banben">
                    <label class="layui-form-label">当前版本：</label>
                    <div class="layui-input-inline">
                        <select name="version" id="version" lay-filter="version"></select>
                    </div>
                    <span class="lastupddt"></span>
                    <span class="isstatus"></span>
                </div>
            </form>
        </div>
        <div class="mapsidediv">
            <div class="page__content">
                <div class="flow-container" style="position: relative">
                    <div id="gaikuai" class="layui-hide">目前流程类型为 自由流程，不支持配置</div>
                    <div class="scale-slider">
                        <i onclick="ratebai(1)" class="fa fa-minus btn" style="color: #777"></i>
                        <span id="ratebai" key="100">100%</span>
                        <i onclick="ratebai(2)" class="fa fa-plus btn" style="color: #777"></i>
                    </div>
                    <div id="mapss" style="display: inline-flex; flex-direction: column; align-items: center; transform: scale(1);">
                        <div id="seccontent">
                            <div class="node-wrap">
                                <div class="node-wrap-box start">
                                    <section class="flow-path-card start-node" onclick="edit_start(0)" key="0">
                                        <header class="header"><div class="title-box"><span class="title-text">开始流程</span></div></header>
                                        <div class="body">
                                            <span class="nonedata"></span>
                                            <span class="text namedata"></span>
                                            <div id="startgai"></div>
                                        </div>
                                    </section>
                                    <div class="add-node-btn-box flex  justify-center">
                                        <div class="add-node-btn">
                                            <span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <section class="flow-path-card-end start-node">结束流程</section>
                        <div id="endgai"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script>


    function set_gaikuai(state=false){
        setTimeout(function () {
            if(state){
                $("#gaikuai").removeClass('layui-hide')

                var gaiStart = document.getElementById('startgai').offsetTop + 80;
                var gaiEnd = document.getElementById('endgai').offsetTop+50

                console.log(gaiStart)
                console.log(gaiEnd)

                $("#gaikuai").css('top', gaiStart)
                $("#gaikuai").css('height', gaiEnd-gaiStart)
            }else{
                $("#gaikuai").addClass('layui-hide')
            }
        },500)
    }



    function layer_close(){
        layer.confirm("<div class='tit'>有正在编辑的中的信息，是否直接关闭窗口？</div><div class='exp'></div>", {
                title:'操作确认',
                icon: 3,
                area:['450px','200px'],
                btn:['确定']
            }, function(conindex){
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            }
        )
    }


    var setName = '';


    var initAddbtnObj;
    var sectionNum = 1;
    var param_classid = getQueryVariable('id') || 0;
    var param_courseid = getQueryVariable('courseid') || 0;
    $(".hei").css('min-height',document.documentElement.clientHeight-100);
    $(".mapsidediv").css('height',document.documentElement.clientHeight-140);
    layui.use(['laytp','form','dropdown', 'util', 'layer', 'table'],function() {
        var dropdown = layui.dropdown
            ,laytp = layui.laytp
            ,util = layui.util
            ,layer = layui.layer
            ,table = layui.table
            ,$ = layui.jquery;
        var form = layui.form;
        get_ajax_course(param_classid, param_courseid);

        function get_ajax_course(classid, id) {
            facade.ajax({type:'GET',url: ask_flow_class_edit,data:{classid:classid,id:id}}).done(function(res){
                if (res['code'] === 2000) {
                    var course = res.data.course;
                    var set = res.data.set;

                    setName = set.name;
                    $('.move_title').text("["+set.name+"]");

                    var list = res.data.list;
                    var startnode = res.data.course.startnode;
                    var sterArr = res.data.course.steparr;
                    show_start_str(startnode, res.data.startInfo);

                    var stepStr = show_step_str(sterArr);
                    $("#seccontent").append(stepStr);

                    var version_str = '';
                    for (var key in list){
                        if(list[key].id == course.id){
                            version_str += '<option value="'+list[key].id+'" selected>'+list[key].vernum+'</option>';
                        }else{
                            version_str += '<option value="'+list[key].id+'">'+list[key].vernum+'</option>';
                        }
                    }
                    $("#version").html(version_str);

                    $(".lastupddt").html('最后修改时间：'+course.updated_at);
                    if(course.status > 0){
                        $(".isstatus").html('<span class="dian" style="background-color: #4CAF50"></span>已发布');
                        $(".isstatus").addClass('colorlv');
                        $(".post_sub_del").hide();
                        $(".post_sub").hide();
                    }else{
                        $(".isstatus").removeClass('colorlv');
                        $(".isstatus").html('<span class="dian" style="background-color: #bbb"></span>未发布');
                        $(".post_sub").show();
                    }
                    init_add_btn();
                    render_from();
                }
            });
        }
        form.on('select(version)',function (data) {
            window.location.href = '/page/flow_class/edit.php?close=1&id='+param_classid+'&courseid='+data.value;
        });


        $(".post_sub_del").click(function () {
            var id = $("#version").val();
            layer.confirm("<div class='tit'>是否确认删除？</div><div class='exp'>删除后不可恢复，请谨慎删除</div>", {
                    title:'操作确认',
                    icon: 3,
                    area:['450px','220px'],
                    btn:['确定']
                }, function(conindex){
                    facade.ajax({url: ask_flow_class_del, data:{id:id}}).done(function(res){
                        if(res.code == 2000){
                            frush_parent();
                            facade.success("提交成功!");
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        }
                    });
                }
            )
            return false;
        });
        $(".post_sub").click(function () {
            var data = get_step_data()
            var id = $("#version").val();

            layer.confirm("<div class='tit'>此操作将更新现有版本，是否继续？</div><div class='exp'></div>", {
                    title:'操作确认',
                    icon: 3,
                    area:['450px','220px'],
                    btn:['确定']
                }, function(conindex){
                    facade.ajax({url: ask_flow_class_edit,data:{id:id, step:data, subtype:1}}).done(function(res){
                        if(res.code == 2000){
                            facade.success("提交成功!");
                            frush_parent();
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        }
                    });
                    layer.close(conindex);
                })

            return false;
        });
        $(".post_sub2").click(function () {
            var data = get_step_data();
            var id = $("#version").val();
            layer.confirm("<div class='tit'>此操作将新建新版本，发布后生效，是否继续？</div><div class='exp'></div>", {
                title:'操作确认',
                icon: 3,
                area:['450px','220px'],
                btn:['确定']
            }, function(conindex){
                facade.ajax({url: ask_flow_class_edit,data:{id:id,step:data, subtype:2}}).done(function(res){
                    if(res.code == 2000){
                        facade.success("提交成功!");
                        frush_parent();
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    }
                });
                layer.close(conindex);
            })

            return false;
        });
        $(".post_sub3").click(function () {
            var data = get_step_data();
            var dataArr = JSON.parse(data);
            if(dataArr[0].data.coursetype != 1){
                if(roverError.length > 0){
                    facade.error("部分节点未设置完毕，请先设置!");
                    for (var iii in roverError){
                        roverError[iii].find('header').addClass('iserrorheader');
                        roverError[iii].find('section').addClass('iserrorsection');
                        // layer.tips("流程节点信息未输入完整", roverError[iii].find('section'), {tips: [1, 'red'], tipsMore: true, time: 3000});
                    }
                    return false;
                }
            }

            var id = $("#version").val();
            layer.confirm("<div class='tit'>流程版本发布后生效，是否继续？</div><div class='exp'></div>", {
                title:'操作确认',
                icon: 3,
                area:['450px','220px'],
                btn:['确定']
            }, function(conindex){
                facade.ajax({url: ask_flow_class_edit,data:{id:id,step:data, subtype:3}}).done(function(res){
                    if(res.code == 2000){
                        facade.success("提交成功!");
                        frush_parent();
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    }
                });
                layer.close(conindex);
            })

            return false;
        });

    });


    function show_start_str(data, startInfo) {
        var nonedata = JSON.stringify(data.data);
        $("section[key=0]").find('.nonedata').html(nonedata);
        if(startInfo){
            var sstr = '';
            sstr += '<p>可见对象：'+startInfo.shentype_name+'</p>';
            sstr += '<p>是否预审：'+startInfo.isadvan_name+'</p>';
            sstr += '<p>通知人：'+startInfo.tonger_name+'</p>';
            sstr += '<p>流程类型：'+startInfo.coursetype_name+'</p>';
            $("section[key=0]").find('.namedata').html(sstr);
        }
        if(startInfo.coursetype == 1){
            set_gaikuai(true);
        }
    }
    function show_step_str(data) {
        var str = '';
        for (var key in data){
            if(data[key].node == 'rover'){
                str += show_step_str_rover(data[key].data, data[key].users_name);
            }else{
                str += show_step_str_term(data[key].data);
            }
        }
        return str;
    }


    function show_step_str_rover(data, users_name) {
        var signtypename = data.signtype == 1 ? '会签' : '或签';
        var str = '';
        str += '<div class="node-wrap">';
        str += '<div class="node-wrap-box approver">';
        str += '<section class="flow-path-card approver" type="rover" key="'+sectionNum+'" onclick="edit_rover('+sectionNum+')">';
        str += '<header class="header">';
        str += '<div class="title-box"><span class="title-text rovname">'+'[ '+signtypename+' ] '+data.rovname+'</span></div>';
        str += '<div class="actions"><span class="shanchu" onclick="shanchu(this, event)"><i class="fa fa-trash-o"></i></span></div>';
        str += '</header>';
        var nonedata = JSON.stringify(data);
        str += '<div class="body"><span class="text rovtitle">'+users_name+'</span><span class="nonedata">'+nonedata+'</span></div>';
        str += '</section>';
        str += '<div class="add-node-btn-box flex  justify-center">';
        str += '<div class="add-node-btn">';
        str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        sectionNum++;
        return str;
    }

    function show_step_str_term(data) {
        var str = '';
        str += '<div class="branch-wrap">';
        str += '<div class="branch-box-wrap">';
        str += '<div class="branch-box  flex justify-center relative">';
        for (var ii in data){
            str += '<div class="col-box">';
            str += '<div class="center-line"></div>';
            str += '<div class="top-cover-line"></div>';
            str += '<div class="bottom-cover-line"></div>';
            str += '<div class="node-wrap">';
            str += '<div class="node-wrap-box condition">';
            str += '<section class="flow-path-card condition" type="term" key="'+sectionNum+'" onclick="edit_term('+sectionNum+')">';
            sectionNum++;
            str += '<header class="header">';
            str += '<div class="title-box">';
            str += '<span class="title-text">条件</span>';
            str += '</div>';
            str += '<span class="priority levelname">优先级'+data[ii].level+'</span>';
            str += '<div class="actions"><span class="shanchutiao" onclick="shanchutiao(this, event)"><i class="fa fa-trash-o"></i></span></div>';
            str += '</header>';
            var nonedata = JSON.stringify({level:data[ii].level, list:data[ii].list});
            str += '<div class="body"><pre class="text valuename">'+data[ii].list_name+'</pre><span class="nonedata">'+nonedata+'</span></div>';
            str += '</section>';
            str += '<div class="add-node-btn-box flex  justify-center">';
            str += '<div class="add-node-btn">';
            str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
            str += '</div>';
            str += '</div>';
            str += '</div>';
            str += '</div>';
            str += show_step_str(data[ii].children);
            str += '</div>';
        }

        str += '</div>';
        str += '<div class="add-node-btn-box flex  justify-center">';
        str += '<div class="add-node-btn">';
        str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        return str;
    }




    var roverError = []; //流程节点信息未输入完整
    function get_step_data() {
        roverError = [];
        var data = [];
        $("#seccontent").children('div').each(function(){
            var divName = $(this).attr('class');
            if(divName === 'node-wrap'){
                var arr = get_node_arr($(this));
                data.push(arr);
            }else{
                var brancharr = get_branch_arr($(this));
                data.push(brancharr);
            }
        });
        return JSON.stringify(data)
    }


    function get_node_arr(obj) {
        var arr = {};
        var nonedata = obj.find('.nonedata').html();
        if(nonedata){
            arr.data = JSON.parse(nonedata);
            if(obj.find('section').attr('key') >= 1){
                if(!arr.data.rovname) {
                    roverError.push(obj);
                }
            }
        }else{
            if(obj.find('section').attr('key') >= 1){
                roverError.push(obj);
            }
            arr.data = [];
        }
        if(obj.find('section').attr('key') < 1){
            arr.node = 'start';
        }else{
            arr.node = 'rover';
        }
        return arr;
    }
    
    function get_branch_arr(obj, arr={}) {
        arr.node = 'term';
        arr.data = [];
        obj.children('div.branch-box-wrap').children('div.branch-box').children('div.col-box').each(function(){
            var colarr = {};
            var nonedata = $(this).children('div:nth-child(4)').find('.nonedata').html();
            if(nonedata){
                colarr = JSON.parse(nonedata);
            }
            colarr.children = [];
            $.each($(this).children('div'), function(key,item){
                if(key > 3){
                    var divName = $(this).attr('class');
                    if(divName === 'node-wrap'){
                        colarr.children.push(get_node_arr($(this)));
                    }else{
                        colarr.children.push(get_branch_arr($(this)));
                    }
                }
            })
            arr.data.push(colarr);
        })
        return arr;
    }
    
    
    
    
    
    
    
    
    


    function init_add_btn() {
        layui.use(['dropdown'],function() {
            var dropdown = layui.dropdown;
            initAddbtnObj = dropdown.render({
                elem: '.addbtn'
                ,align: 'center'
                ,data: [
                    {id: 'node',templet: '<span class="iconbut"><i class="fa fa-thumb-tack"></i></span> <br>审批节点'}
                    ,{id: 'term',templet: '<span class="iconbut"><i class="fa fa-gears"></i></span> <br>添加条件'}
                ],click: function(obj){
                    if(obj.id == 'node'){
                        var str = '';
                        str += '<div class="node-wrap">';
                        str += '<div class="node-wrap-box approver">';
                        str += '<section class="flow-path-card approver" type="rover" key="'+sectionNum+'" onclick="edit_rover('+sectionNum+')">';
                        str += '<header class="header">';
                        str += '<div class="title-box"><span class="title-text rovname">审批人</span></div>';
                        str += '<div class="actions"><span class="shanchu" onclick="shanchu(this, event)"><i class="fa fa-trash-o"></i></span></div>';
                        str += '</header>';
                        var nonedata = JSON.stringify({rovname:'',signtype:1,rovedit:0,users:'',shentype:'',plain:0});
                        str += '<div class="body"><span class="text rovtitle">请设置审批人</span><span class="nonedata">'+nonedata+'</span></div>';
                        str += '</section>';
                        str += '<div class="add-node-btn-box flex  justify-center">';
                        str += '<div class="add-node-btn">';
                        str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
                        str += '</div>';
                        str += '</div>';
                        str += '</div>';
                        str += '</div>';
                        sectionNum++;
                        var obj = $(this.elem).parents('.add-node-btn-box').parent('div').parent('div.node-wrap');
                        if(obj.length < 1){
                            obj = $(this.elem).parents('.add-node-btn-box').parent('div').parent('div.branch-wrap');
                        }
                        obj.after(str);
                    }

                    if(obj.id == 'term'){
                        var str = '';
                        var obj = $(this.elem).parents('.add-node-btn-box').parent('div').parent('div.node-wrap');
                        if(obj.length < 1){
                            obj = $(this.elem).parents('.add-node-btn-box').parent('div').parent('div.branch-wrap');
                        }
                        var nextobj = obj.next();
                        if(nextobj.hasClass('branch-wrap')){
                            var colnum = nextobj.find('.col-box').length + 1;
                            str += get_term_str(colnum);
                            nextobj.find('.col-box:last-child').after(str);
                        }else{
                            str += '<div class="branch-wrap">';
                            str += '<div class="branch-box-wrap">';
                            str += '<div class="branch-box  flex justify-center relative">';
                            str += get_term_str(1);
                            str += get_term_str(2);
                            str += '</div>';
                            str += '<div class="add-node-btn-box flex  justify-center">';
                            str += '<div class="add-node-btn">';
                            str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
                            str += '</div>';
                            str += '</div>';
                            str += '</div>';
                            str += '</div>';

                            obj.after(str);
                        }
                    }
                    init_add_btn();
                }
            });
        });
    }

    function get_term_str(num) {
        var str = '';
        str += '<div class="col-box">';
        str += '<div class="center-line"></div>';
        str += '<div class="top-cover-line"></div>';
        str += '<div class="bottom-cover-line"></div>';
        str += '<div class="node-wrap">';
        str += '<div class="node-wrap-box condition">';
        str += '<section class="flow-path-card condition" type="term" key="'+sectionNum+'" onclick="edit_term('+sectionNum+')">';
        str += '<header class="header">';
        str += '<div class="title-box">';
        str += '<span class="title-text">条件</span>';
        str += '</div>';
        str += '<span class="priority levelname">优先级'+num+'</span>';
        str += '<div class="actions"><span class="shanchutiao" onclick="shanchutiao(this, event)"><i class="fa fa-trash-o"></i></span></div>';
        str += '</header>';
        var nonedata = JSON.stringify({level: num, list:[]});
        str += '<div class="body"><pre class="text valuename">无条件</pre><span class="nonedata">'+nonedata+'</span></div>';
        str += '</section>';
        str += '<div class="add-node-btn-box flex  justify-center">';
        str += '<div class="add-node-btn">';
        str += '<span><button type="button" class="btn addbtn"><i class="fa fa-plus"></i></button></span>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        str += '</div>';
        sectionNum++;
        return str;
    }

    function shanchu(obj, event) {
        event.stopPropagation();
        $(obj).parents('.node-wrap').remove();
    }

    function shanchutiao(that, event) {
        event.stopPropagation();
        var obj = $(that).parents('section').parent('div').parent('div').parent('div.col-box');
        var sibObj = obj.siblings();
        if(sibObj.length > 1){
            obj.remove();
        }else{
            sibObj.children('div:nth-child(1)').remove();
            sibObj.children('div:nth-child(1)').remove();
            sibObj.children('div:nth-child(1)').remove();
            sibObj.children('div:nth-child(1)').remove();
            if(sibObj.html()){
                sibObj.parent('div').parent('div').parent('div.branch-wrap').before(sibObj.html());
                sibObj.parent('div').parent('div').parent('div.branch-wrap').remove();
                init_add_btn();
            }else{
                sibObj.parent('div').parent('div').parent('div.branch-wrap').remove();
            }

        }
    }

    function edit_start(sectionnum) {
        openPage('edit_start.php?sectionnum='+sectionnum+'&name='+encodeURI(setName), '770px', '490px');
    }

    function edit_term(sectionnum) {
        openPage('edit_term.php?sectionnum='+sectionnum+'&classid='+param_classid,'80%', '80%');
    }

    function edit_rover(sectionnum) {
        openPage('edit_rover.php?sectionnum='+sectionnum+'&classid='+param_classid, '770px', '490px');
    }


    function ratebai(type) {
        var key = parseInt($("#ratebai").attr('key'));
        if(type == 1){
            if(key <= 5){
                return false;
            }
            var ratebai = key-5;
        }else{
            if(key >= 200){
                return false;
            }
            var ratebai = key+5;
        }
        $("#mapss").css('transform','scale('+(ratebai/100)+')');
        $("#ratebai").html(ratebai+'%').attr('key', ratebai);
    }



    function frush_parent(){
        if (typeof(window.parent.get_data)!="undefined"){
            window.parent.get_data();
        }
    }


</script>
</body>
</html>